<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>编辑用户</span>
          <el-button @click="goBack" plain>返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="用户ID">
          <el-input v-model="userForm.user_id" disabled />
        </el-form-item>

        <el-form-item label="昵称" prop="nick_name">
          <el-input v-model="userForm.nick_name" />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" />
        </el-form-item>

        <el-form-item label="积分" prop="points">
          <el-input-number v-model="userForm.points" :min="0" />
        </el-form-item>

        <el-form-item label="使用次数" prop="usage_count">
          <el-input-number v-model="userForm.usage_count" :min="0" />
        </el-form-item>

        <el-form-item label="用户角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择用户角色">
            <el-option label="普通用户" value="user" />
            <el-option label="分销者" value="commission" />
          </el-select>
        </el-form-item>

        <el-form-item label="分销比例 (%)" prop="distribution_rate">
          <el-input-number
            v-model="userForm.distribution_rate"
            :min="0"
            :max="100"
            :step="0.01"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="创建时间">
          <div>{{ formatDate(userForm.create_time) }}</div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getUserDetail, updateUser } from "@/api/user";

const route = useRoute();
const router = useRouter();
const userId = route.params.id;

const formRef = ref(null);
const loading = ref(false);

const userForm = reactive({
  user_id: "",
  nick_name: "",
  mobile: "",
  points: 0,
  usage_count: 0,
  role: "user", // 默认普通用户
  distribution_rate: 0, // 分销比例，百分比
  create_time: "",
});

const rules = {
  nick_name: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  mobile: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号码",
      trigger: "blur",
    },
  ],
  role: [{ required: true, message: "请选择用户角色", trigger: "change" }],
  distribution_rate: [
    {
      type: "number",
      min: 0,
      max: 100,
      message: "分销比例必须在0-100之间",
      trigger: "blur",
    },
  ],
};

const fetchUserDetail = async () => {
  if (!userId) return;
  loading.value = true;
  try {
    const res = await getUserDetail(userId);
    if (res.data) {
      Object.assign(userForm, res.data);
      // 防止后端未返回分销比例，初始化为0
      if (userForm.distribution_rate == null) userForm.distribution_rate = 0;
      if (!userForm.role) userForm.role = "user";
    }
  } catch (error) {
    console.error("获取用户详情失败", error);
    ElMessage.error("获取用户详情失败");
  } finally {
    loading.value = false;
  }
};

const submitForm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;
    await updateUser(userId, userForm);
    ElMessage.success("保存成功");
    goBack();
  } catch (error) {
    console.error("保存失败", error);
    ElMessage.error("保存失败");
  } finally {
    loading.value = false;
  }
};

const goBack = () => {
  router.push("/user/list");
};

const formatDate = (dateStr) => {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  return date.toLocaleString();
};

onMounted(() => {
  fetchUserDetail();
});
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
